# frozen_string_literal: true

class RulesEngineSchema < GraphQL::Schema
  mutation(GqlTypes::MutationType)
  query(GqlTypes::QueryType)

  # Opt in to the new runtime (default in future graphql-ruby versions)
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST

  # Add built-in connections for pagination
  use GraphQL::Pagination::Connections

  use GraphQL::Batch

  lazy_resolve Promise, :sync

  rescue_from(ActiveRecord::RecordNotFound) { 'Not found' }

  class << self
    def object_from_id(_unique_id, context, _opts = {})
      context[:klass].find(id)
    end

    def object_from_encrypted_id(encrypted_id, context, opts = {})
      object_from_id parse_encrypted_id(encrypted_id), context, opts
    end

    def encode_base64(value)
      Base64.encode64(value).sub(/=*\n$/, '')
    end

    def decode_base64(value)
      Base64.decode64(value)
    end

    private

    def parse_encrypted_id(id)
      id = Base64.decode64(id)
      id.match(/(?<id>\d+$)/)&.[](:id) && id
    end

    # class InvalidRelayIdRequestError < StandardError; end
    # def id_from_object(obj, type_name, _context)
    #   if obj.respond_to?(:to_relay_id)
    #     id = obj.to_relay_id
    #   elsif obj.respond_to?(:id)
    #     id = obj.id
    #   elsif obj.respond_to?(:[])
    #     id = obj["id"] || obj[:id]
    #   end
    #   if id.blank?
    #     error = InvalidRelayIdRequestError.new("Cannot generate relay id for #{type_name} object")
    #     Stats::Infra.error("graphql", "relay_schema_id_from_object", error)
    #     ErrorLogger.error(error)
    #   end
    #   padded = Base64.strict_encode64("#{type_name}/#{id}")
    #   return padded.gsub(/=+$/, "")
    # end
  end
end
